from flask import current_app, jsonify
from flask import render_template
from flask import request

from cyds import db
from cyds.models import News, Squad, Applicant, Category
from . import index_blu


@index_blu.route('/apply', methods=['POST'])
def apply():
    """报名入口"""
    school = request.form.get('school')
    name = request.form.get('name')
    profession = request.form.get('profession')
    grade = request.form.get('grade')

    if not all([school, name, grade, profession]):
        return jsonify(errno=404, errmsg="参数不足")

    applicant = Applicant()
    applicant.name = name
    applicant.school = school
    applicant.profession = profession
    applicant.grade = grade

    try:
        db.session.add(applicant)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=500, errmsg="数据存储失败")

    return jsonify(errno=200, errmsg="OK")


@index_blu.route('/group')
def group():
    """首页小组作品展示"""
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '8')
    category_id = request.args.get('category_id', "2")

    try:
        page = int(page)
        per_page = int(per_page)
        category_id = int(category_id)

    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=403, errmsg="参数错误")

    try:
        school = Category.query.get(category_id)
        paginate = Squad.query.filter_by(school=school.id).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=404, errmsg="数据查询错误")

    # 取到当前页的数据
    squad_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    # 将模型对象列表转成字典列表
    group_dict_li = []
    for squad in squad_model_list:
        squad_dict = {
            "id": squad.id,
            "name": squad.name,
            "school": squad.school,
            "video_url": squad.video_url
        }
        group_dict_li.append(squad_dict)

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "group_dict_li": group_dict_li
    }

    return jsonify(errno=200, errmsg="OK", data=data)


@index_blu.route('/news')
def news():
    """首页新闻"""
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '5')

    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=403, errmsg="参数错误")

    try:
        paginate = News.query.filter().order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=404, errmsg="数据查询错误")

    # 取到当前页的数据
    news_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    # 将模型对象列表转成字典列表
    news_dict_li = []
    for news_list in news_model_list:
        news_dict = {
            "id": news_list.id,
            "title": news_list.title,
            "content": news_list.content,
            "image_url": news_list.image_url
        }
        news_dict_li.append(news_dict)

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li
    }

    return jsonify(errno=200, errmsg="OK", data=data)


@index_blu.route('/')
def index():

    return render_template("front/index.html")


# 在打开网页的时候，浏览器会默认去请求根路径+favicon.ico作网站标签的小图标
# send_static_file 是 flask 去查找指定的静态文件所调用的方法
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('/favicon.ico')